package com.hernie.piggymall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hernie.common.utils.R;
import com.hernie.piggymall.cart.feign.ProductFeignService;
import com.hernie.piggymall.cart.interceptor.CartInterceptor;
import com.hernie.piggymall.cart.service.CartService;
import com.hernie.piggymall.cart.to.UserInfoTo;
import com.hernie.piggymall.cart.vo.CartItemVo;
import com.hernie.piggymall.cart.vo.CartVo;
import com.hernie.piggymall.cart.vo.SkuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.ParameterResolutionDelegate;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Author HuangJp
 * @Date 2022/4/20
 * @Description
 */
@Service("cartService")
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    
    private final String CART_PREFIX = "piggymall:cart:";
    
    @Override
    public CartItemVo addCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String sku = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(sku)) {
            // 购物车无此商品
            // 添加新商品到购物车
            CartItemVo cartItem = new CartItemVo();
            // 远程查询当前要添加的商品信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setPrice(data.getPrice());
                cartItem.setSkuId(skuId);
            }, executor);

            // 远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttrValues(values);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();    // 阻塞等待异步任务完成
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), s);

            return cartItem;
        } else {
            // 购物车有此商品，修改数量
            CartItemVo cartItem = JSON.parseObject(sku, CartItemVo.class);
            cartItem.setCount(cartItem.getCount() + num);

            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String str = (String) cartOps.get(skuId.toString());
        CartItemVo cartItem = JSON.parseObject(str, CartItemVo.class);

        return cartItem;
    }

    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cart = new CartVo();
        // 区分登陆状态，是用户登录还是临时用户
        // 得到当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId() != null) {
            // 已登录的用户
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            // 如果临时购物车的数据还没有进行合并
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItemVo> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null) {
                // 临时购物车中有数据，需要合并
                for (CartItemVo item : tempCartItems) {
                    addCart(item.getSkuId(), item.getCount());
                }
                // 合并完成后清除临时购物车的数据
                clearCart(tempCartKey);
            }

            // 获取登陆后的购物车数据 【合并后的数据,包含临时购物车的数据】
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            // 临时用户
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            // 获取临时购物车所有购物项
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 获取到我们要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 得到当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        // 设置redis中购物车的key
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            // 登录用户购物车
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            // 临时用户购物车
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        // 获取redis对cartKey的操作对象
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    /**
     * 获取购物车中的所有购物项
     * @param cartKey
     * @return
     */
    private List<CartItemVo> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItemVo> cartItemVos = values.stream().map(obj -> {
                String str = (String) obj;
                CartItemVo cartItem = JSON.parseObject(str, CartItemVo.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItemVos;
        }
        return null;
    }

    /**
     * 清空购物车
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), s);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItemVo> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItemVo> cartItems = getCartItems(cartKey);
            // 获取所有被选中的购物项
            List<CartItemVo> collect = cartItems.stream()
                    .filter(CartItemVo::getCheck).map(item -> {
                        BigDecimal price = productFeignService.getPrice(item.getSkuId());
                        // 更新为最新价格
                        item.setPrice(price);
                        return item;
                    })
                    .collect(Collectors.toList());
            return collect;
        }
    }
}
